import { Injectable } from '@nestjs/common';
import { PrismaService } from 'src/common/prisma/PrismaService';
import ExamRoomQueryParam from '../param/ExamRoomQueryParam';
import ExamRoomVo from '../vo/ExamRoomVo';
import { plainToInstance } from 'class-transformer';
import ExamRoomDto from '../dto/ExamRoomDto';
import ServiceException from 'src/common/ServiceException';

/*
 * @Author: jingfuu@163.com
 * @Date: 2024-12-16 12:52:28
 * @LastEditTime: 2024-12-16 13:13:33
 * @Description: 考场
 */
@Injectable()
class ExamRoomService {
  constructor(private readonly prisma: PrismaService) {}

  async detail(id: number) {
    const examRoom = await this.prisma.examRoom.findUnique({
      where: {
        id,
      },
    });
    return plainToInstance(ExamRoomVo, examRoom);
  }
  async list(param: ExamRoomQueryParam) {
    const skip = param.pageNum != 0 ? (param.pageNum - 1) * param.pageSize : 0;
    const whereClause: any = this.generatePageQueryCondition(param);
    const [total, list] = await this.prisma.$transaction([
      this.prisma.examRoom.count({ where: whereClause }),
      this.prisma.examRoom.findMany({
        skip,
        take: param.pageSize,
        orderBy: {
          createTime: 'desc',
        },
        where: whereClause,
      }),
    ]);
    const rows: ExamRoomVo[] = plainToInstance(ExamRoomVo, list);
    return {
      total,
      rows,
    };
  }
  generatePageQueryCondition(param: ExamRoomQueryParam) {
    const whereClause: any = {};
    if (param.name) {
      whereClause.name = {
        contains: param.name,
      };
    }
    if (param.districtId) {
      whereClause.districtId = param.districtId;
    }
    return whereClause;
  }

  async edit(examRoom: ExamRoomDto) {
    await this.checkExamRoomName(examRoom.name, examRoom.id);
    await this.prisma.examRoom.update({
      data: {
        name: examRoom.name,
        districtId: examRoom.districtId,
      },
      where: {
        id: examRoom.id,
      },
    });
  }
  async checkExamRoomName(name: string, id: number) {
    const examRoom = await this.prisma.examRoom.findFirst({
      where: {
        name: name,
      },
    });
    if (!id) {
      if (examRoom) {
        throw new ServiceException('考场：' + name + '已存在');
      }
    } else {
      if (examRoom && examRoom.id != id) {
        throw new ServiceException('考场：' + name + '已存在');
      }
    }
  }
  async remove(id: number) {
    await this.prisma.examRoom.delete({ where: { id } });
  }
  async add(examRoom: ExamRoomDto) {
    await this.checkExamRoomName(examRoom.name, examRoom.id);
    await this.prisma.examRoom.create({
      data: {
        name: examRoom.name,
        districtId: examRoom.districtId,
      },
    });
  }
}
export default ExamRoomService;
